<?php
$output = array();

if (!isset($_GET["searchWord"])) {
    echo("No search parameter specified");
    exit();
}
if (isset($_GET["searchField"])) {
    $searchField = $_GET["searchField"];
}
$searchWord = $_GET["searchWord"];

// import database connection variables and connectToMysql method
require_once __DIR__ . '/db_config.php';

$mysqli = connectToMysql();

if (isset($searchField)) {
    $query = "select company.id, company.name, company.description, company.profile, company.companyUrl,
        location.latitude, location.longitude from Company company left join Location location on company.location = location.id
        where " . $searchField . " like '%" . $searchWord . "%'";
} else {
    $query = "select company.id, company.name, company.description, company.profile, company.companyUrl, company.averageRating,
        location.latitude, location.longitude from Company company left join Location location on company.location = location.id
        where "
        . "name like '%" . $searchWord . "%'"
        . " or description like '%" . $searchWord . "%'"
        . " or profile like '%" . $searchWord . "%'";

}

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($row = $result->fetch_assoc()) {
        $output[] = array_map('utf8_encode', $row);
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
// this will print the output in json
$finalResult = json_encode($output, JSON_NUMERIC_CHECK);
$finalResult = str_replace('"latitude":""', '"latitude":NULL', $finalResult);
$finalResult = str_replace('"longitude":""', '"longitude":NULL', $finalResult);
$finalResult = str_replace('"averageRating":""', '"averageRating":null', $finalResult);


echo $finalResult;
?>